package com.shopper.manager.controller;

import com.auth0.jwt.JWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shopper.manager.config.ConfigCode;
import com.shopper.manager.config.RequestCode;
import com.shopper.manager.config.RequestMassage;
import com.shopper.manager.mapper.BaseMapper;
import com.shopper.manager.model.BaseBean;
import com.shopper.manager.model.customer.req.CustomerInfoReq;
import com.shopper.manager.model.customer.req.RegisteredReq;
import com.shopper.manager.model.index.UserBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseController {

    @Autowired
    public BaseMapper baseMapper;

    public String getsBaseBean(int code, String message, Object data) throws JsonProcessingException {

        return new ObjectMapper().writeValueAsString(new BaseBean(code, message, data));
    }

    /**
     * 时间处理
     */
    private void timeSql(){
//        https://blog.csdn.net/weixin_30418225/article/details/113225286
//        SELECT hour(timediff(clockTime,afterWorkTime))+minute(timediff(clockTime,afterWorkTime))/60 AS datetime FROM user_clock WHERE DATE_FORMAT(clockDate,'%Y-%c') = '2022-3' and userAccount='13333333333' and businessLicense='GJ9796154846464646'
//
//        SELECT hour(timediff(clockTime,afterWorkTime))+minute(timediff(clockTime,afterWorkTime))/60 AS datetime FROM user_clock WHERE DATE_FORMAT(clockTime,'%T') <= '08:30:00' and userAccount='13333333333' and businessLicense='GJ9796154846464646'
    }


    /**
     * 获取uid
     *
     * @return
     */
    public int getUid(Map<String, String> header) {
        return Integer.valueOf(getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(0));
    }

    public List<String> getTokenCode(String token) {
        return JWT.decode(token).getAudience();
    }

    /**
     * 获取当前日期
     *
     * @return
     */
    public String getCurrentDate(String time) {
        //"yyyy-MM-dd HH:mm:ss"
        SimpleDateFormat df = new SimpleDateFormat(time);
        return df.format(new Date());
    }

    /**
     * 获取年月日
     *
     * @return
     */
    public String getYearMonthDay(String time) {

        try {
            Date  df = new SimpleDateFormat("yyyy-MM-dd").parse(time);
            Calendar ca = Calendar.getInstance();
            ca.setTime(df);
            int day = ca.get(Calendar.DATE);//一年中的第几天
            int month = ca.get(Calendar.MONTH)+1;//第几个月
            if (month>12){
                month=0;
            }
            int year = ca.get(Calendar.YEAR);//年份数值
            return String.format("%s-%s-%s",year,month,day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String toDate(String time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            Date  date = new SimpleDateFormat("yyyy-MM-dd").parse(time);
            String s = sdf.format(date); // 把带时分秒的 date 转为 yyyy-MM-dd 格式的字符串
            Date date2 = sdf.parse(s); // 把上面的字符串解析为日期类型
            return sdf.format(date2);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }

    }

    public Date getDate(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
            dateTime = df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return dateTime;
    }


    /**
     * 处理商家token问题
     *
     * @param header
     * @return
     * @throws JsonProcessingException
     */
    public String processToken(Map<String, String> header) throws JsonProcessingException {


        if (header == null) {
            return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
        } else if (header.get(ConfigCode.HEADER_TOKEN_KEY) == null || header.get(ConfigCode.HEADER_TOKEN_KEY).isEmpty()) {
            return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
        }

        UserBean userBean = baseMapper.getTokenBean(header.get(ConfigCode.HEADER_TOKEN_KEY));
        if (userBean == null) {
            return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
        }

        String uid = getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(0);
        String date = getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(1);
        if (uid != null && !uid.isEmpty() && date != null && !date.isEmpty()) {
            try {
                boolean isTrue = convert(getDate(date), getDate(getCurrentDate("yyyy-MM-dd HH:mm:ss")));
                if (isTrue) {
                    return ConfigCode.TOKEN_OK;
                }
            } catch (Exception e) {
                return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
            }


        }

        return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
    }



    /**
     * 处理用户端token问题
     *
     * @param header
     * @return
     * @throws JsonProcessingException
     */
    public String processCustomerToken(Map<String, String> header) throws JsonProcessingException {


        if (header == null) {
            return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
        } else if (header.get(ConfigCode.HEADER_TOKEN_KEY) == null || header.get(ConfigCode.HEADER_TOKEN_KEY).isEmpty()) {
            return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
        }

        CustomerInfoReq userBean = baseMapper.getCustomTokenBean(header.get(ConfigCode.HEADER_TOKEN_KEY));
        if (userBean == null) {
            return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
        }

        String uid = getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(0);
        String date = getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(1);
        if (uid != null && !uid.isEmpty() && date != null && !date.isEmpty()) {
            try {
                boolean isTrue = convert(getDate(date), getDate(getCurrentDate("yyyy-MM-dd HH:mm:ss")));
                if (isTrue) {
                    return ConfigCode.TOKEN_OK;
                }
            } catch (Exception e) {
                return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
            }


        }

        return getsBaseBean(RequestCode.ERROR_TOKEN_FAILURE, RequestMassage.TOKEN_FAILURE, null);
    }




    public boolean convert(Date startDate, Date endDate) {
        long startTime = startDate.getTime();//获取毫秒数
        long endTime = endDate.getTime();     //获取毫秒数
        long timeDifference = endTime - startTime;
        long second = timeDifference / 1000;    //计算秒

        long hours = second * 60 * 60;
        return second <= hours ? true : false;

//        if(second<60) {
//            return second+"秒前";
//        }else {
//            long minute = second/60;
//            if(minute<60) {
//                return minute+"分钟前";
//            }else {
//                long hour = minute/60;
//                if(hour<24) {
//                    return hour+"时前";
//                }else {
//                    long day = hour/24;
//                    if(day<30) {
//                        return day+"天前";
//                    }else {
//                        long month = day/30;
//                        if(month<12) {
//                            return day+"月前";
//                        }else {
//                            long year = month/12;
//                            return year+"年前";
//                        }
//                    }
//
//                }
//            }
//        }
    }


    public String returnResultInfo(int code) throws JsonProcessingException {
        return returnResultInfo(code, null);
    }

    public String returnResultInfo(int code, Object data) throws JsonProcessingException {
        switch (code) {
            case RequestCode.SUCCESS_CODE:

                return getsBaseBean(RequestCode.SUCCESS_CODE, RequestMassage.REQUEST_SUCCESS, data);
            case RequestCode.ERROR_UPLOAD_CODE:

                return getsBaseBean(RequestCode.ERROR_UPLOAD_CODE, RequestMassage.UPLOAD_CODE_ERROR, data);
            case RequestCode.ERROR_DELETE_FAILED:

                return getsBaseBean(RequestCode.ERROR_DELETE_FAILED, RequestMassage.DELETE_FAILED, data);
            case RequestCode.ERROR_UPDATE_FAILED:

                return getsBaseBean(RequestCode.ERROR_UPDATE_FAILED, RequestMassage.UPDATE_DATA_FAILED, null);
            case RequestCode.ERROR_ACCOUNT_REPEAT:
                return getsBaseBean(RequestCode.ERROR_ACCOUNT_REPEAT, RequestMassage.ACCOUNT_NOT_FIND, null);
            case RequestCode.ERROR_UNKNOWN:
                return getsBaseBean(RequestCode.ERROR_UNKNOWN, RequestMassage.UNKNOWN_ERROR, null);
            case RequestCode.ERROR_SELECT_FAILED:

                return getsBaseBean(RequestCode.ERROR_SELECT_FAILED, RequestMassage.SELECT_FAILED, null);
            case RequestCode.ERROR_NOT_PERMISSIONS:

                return getsBaseBean(RequestCode.ERROR_NOT_PERMISSIONS, RequestMassage.NOT_FIND_PERMISSIONS, null);
            case RequestCode.ERROR_PASSWORD:

                return getsBaseBean(RequestCode.ERROR_PASSWORD, RequestMassage.PASSWORD_ERROR, null);
            case RequestCode.ERROR_FILE_NOT_EXIST:
                return getsBaseBean(RequestCode.ERROR_FILE_NOT_EXIST, RequestMassage.FILE_NOT_EXIST, null);
            case RequestCode.ERROR_UPLOAD_FAILURE:
                return getsBaseBean(RequestCode.ERROR_UPLOAD_FAILURE, RequestMassage.FILE_UPLOAD_FAILURE, null);
            case RequestCode.ERROR_RESET_COMMIT:
                return getsBaseBean(RequestCode.ERROR_RESET_COMMIT, RequestMassage.RESET_COMMIT, null);

            default:
                throw new IllegalStateException("Unexpected value: " + code);
        }
    }

    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public  boolean isEmpty( CharSequence str) {
        return str == null || str.length() == 0;
    }
}

